import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Modal, Popconfirm, Button, message, Table, Image } from 'antd';
import { MenuOutlined } from '@ant-design/icons';
import { arrayMoveImmutable } from 'array-move';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';

const mapStateToProps = (state: any) => ({
  contentMng: state.contentMng,
  menu: state.menu,
  loading: state.loading.models['contentMng'],
});
const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

class ContentSortModal extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      contentDetailData: props.contentDetails,
      imgList: props.imgList.map((item: any, index: number) => {
        return {
          ...item,
          index,
          key: index + '',
        };
      }),
    };
  }

  onSortEnd = ({ oldIndex, newIndex }: any) => {
    const dataSource = this.state.imgList;
    console.log(oldIndex, newIndex, dataSource);
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el: any) => !!el,
      );
      console.log('Sorted items: ', newData);
      // setDataSource(newData);
      console.log(newData);
      this.setState({
        imgList: newData,
      });
    }
  };
  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };
  confirmSort = () => {
    const { dispatch, closeModal } = this.props;
    const { imgList, contentDetailData } = this.state;
    const detailData = JSON.parse(contentDetailData.contentJson);
    detailData.splice(
      detailData.find((item: { type: string }) => item.type == '3'),
      1,
      {
        type: '3',
        content: imgList.map((item: { src: any }) => {
          return {
            ...item.src,
          };
        }),
      },
    );
    const params = { ...contentDetailData, contentJson: JSON.stringify(detailData) };
    console.log(params);
    dispatch({
      type: 'contentMng/editTempContent',
      payload: {
        ...params,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          this.close();
          message.success('保存成功');
        }
      },
    });
  };
  handleDel = (record: any, index: number): void => {
    const list = this.state.imgList;
    list.splice(index, 1);
    this.setState({ imgList: [...list] });
  };
  render() {
    const { modalVisible, loading } = this.props;
    const { imgList } = this.state;
    const dataSource = imgList;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.confirmSort} type="primary">
          确定
        </Button>
      </div>
    );
    const columns: Array<any> = [
      {
        title: '图片',
        dataIndex: 'src',
        className: 'drag_visible',
        render: (text: any, record: any) => {
          return (
            <Image
              src={text.url}
              style={{ width: 75, height: 30, marginLeft: 5, marginTop: 5 }}
              fallback=""
            />
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        className: 'drag_visible',
        render: (text: any, record: any, index: number) => {
          return (
            <span>
              <Popconfirm
                title="是否确认删除图片?"
                onConfirm={() => this.handleDel(record, index)}
                okText="是"
                cancelText="否"
              >
                <Button
                  style={{ marginRight: 5 }}
                  size="small"
                  ghost
                  type="primary"
                  disabled={imgList.length < 3}
                >
                  删除
                </Button>
              </Popconfirm>
            </span>
          );
        },
      },
      {
        title: '',
        dataIndex: 'sort',
        width: 30,
        className: 'drag_visible',
        render: () => <DragHandle />,
      },
    ];
    const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
      <tr {...props} />
    ));
    const SortableBody = SortableContainer(
      (props: React.HTMLAttributes<HTMLTableSectionElement>) => <tbody {...props} />,
    );
    const DraggableContainer = (props: any) => (
      <SortableBody
        useDragHandle
        disableAutoscroll
        helperClass="row_dragging"
        onSortEnd={this.onSortEnd}
        {...props}
      />
    );
    const DraggableBodyRow: React.FC<any> = ({ className, style, ...restProps }) => {
      // function findIndex base on Table rowKey props and should always be a right array index
      const index = dataSource.findIndex(x => x.index === restProps['data-row-key']);
      return <SortableItem index={index} {...restProps} />;
    };
    return (
      <Modal
        width={580}
        footer={footer}
        title="图片详情"
        visible={modalVisible}
        onCancel={this.close}
      >
        <>
          {imgList.map((item: any, index: number) => <div key={index} style={{
            display: 'inline-block',
            marginLeft: 15,
            marginTop: 10,
            marginBottom: 10
          }}>
            <Image src={item.src.url} style={{
              width: 150,
              height: 60
            }} fallback="" />
          </div>)}
        </>
        {/* <Table
          pagination={false}
          showHeader={false}
          dataSource={dataSource}
          columns={columns}
          rowKey="index"
          components={{
            body: {
              wrapper: DraggableContainer,
              row: DraggableBodyRow,
            },
          }}
        /> */}
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(ContentSortModal);
